<template>
  <view>
    <view class="title">微信小程序</view>
    <view class="container-null">
      <u-button type="success" size="default" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" style="margin-top: 20px;">
        微信小程序授权登录
      </u-button>
    </view>
  </view>
</template>

<script>
let that;

export default {
  data() {
    return {
      form: {
        code: '',
        rawData: '',
        signature: '',
        encryptedData: '',
        iv: '',
        nickName: '',
        avatarUrl: '',
        gender: '',
      }
    }
  },
  onLoad() {
    that = this;
    that.getCode();
  },
  methods: {
    getCode() {
      wx.login({
        success(res) {
          if (res.code) {
            that.form.code = res.code;
          } else {
            that.$msg('登录失败：' + res.errMsg);
          }
        },
        fail(err) {
          that.$msg('code获取失败');
        },
      });
    },
    getPhoneNumber(e) {
      that.getCode();
      if (e.detail.errMsg != 'getPhoneNumber:ok') {
        that.$msg('未授权手机号');
        return false;
      }
      that.form.encryptedData = e.detail.encryptedData;
      that.form.iv = e.detail.iv;
      // 检查登录态是否过期
      wx.checkSession({
        success() {
          // 用户信息
          wx.getUserInfo({
            success: function(result) {
              that.form.rawData = result.rawData;
              that.form.signature = result.signature;
              that.form.nickName = result.userInfo.nickName;
              that.form.avatarUrl = result.userInfo.avatarUrl;
              that.form.gender = result.userInfo.gender;
              uni.$u.http.post('/app/login/common/weChatMiniappLogin', that.form).then(res => {
                uni.setStorageSync(that.$config.cachePrefix + 'token', res.token);
                uni.$u.http.get('/app/login/getInfo').then(result => {
                  uni.setStorageSync(that.$config.cachePrefix + 'user', result.user);
                  uni.setStorageSync(that.$config.cachePrefix + 'roles', result.roles);
                  uni.setStorageSync(that.$config.cachePrefix + 'permissions', result.permissions);
                  that.$msg('登录成功', function () {
                    uni.$u.route({url: '/pages/index/index'});
                  });
                });
              });
            }
          });
        },
        fail(err) {
          wx.login({
            success: res => {
              that.form.code = res.code
            }
          });
        }
      });
    },
  },
}
</script>

<style lang="scss" scoped>
.title {
  font-size: 18px;
  text-align: center;
  line-height: 200px;
}
</style>
